<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAdd">新建</el-button>

    <el-table :data="list" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="类型ID" min-width="50">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="品牌" min-width="50">
        <template slot-scope="scope">
          {{ scope.row.brand }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="型号" min-width="50">
        <template slot-scope="scope">
          {{ scope.row.model }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="座位数量" min-width="50">
        <template slot-scope="scope">
          {{ scope.row.seats }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="城市" min-width="50">
        <template slot-scope="scope">
          {{ scope.row.city }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="图片" min-width="100">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.imgUrl"
            fit="fit"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="描述" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.typeDesc }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑':'新建'">
      <el-form :model="scopeData" label-width="80px" label-position="left">
        <el-form-item label="品牌">
          <el-input v-model="scopeData.brand" placeholder="请输入品牌"/>
        </el-form-item>
        <el-form-item label="型号">
          <el-input v-model="scopeData.model" placeholder="请输入型号"/>
        </el-form-item>
        <el-form-item label="座位数量">
          <el-input v-model="scopeData.seats" placeholder="请输入座位数量"/>
        </el-form-item>
        <el-form-item label="城市">
          <el-input v-model="scopeData.city" placeholder="请输入城市"/>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            :headers="uploadHeader"
            class="avatar-uploader"
            action="http://localhost:8888/manager/index/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :with-credentials="true">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="scopeData.typeDesc" placeholder="描述"/>
        </el-form-item>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deleteCarType, getCarTypeList, insertOrUpdateCarType } from '@/api/car'
import { getToken } from '@/utils/auth'

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  name: 'CarType',
  data() {
    return {
      role: Object.assign({}, defaultRole),
      list: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      checkedRole: [],
      scopeData: {},
      multipleSelection: [],
      isChangePassword: true,
      isAddModel: false,
      imageUrl: ''
    }
  },
  computed: {
    uploadHeader() {
      return {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      const res = await getCarTypeList()
      console.log(res)
      this.list = res.data
    },
    handleAdd() {
      this.imageUrl = ''
      this.isChangePassword = false
      this.isAddModel = true
      this.scopeData = {}
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.imageUrl = scope.imgUrl
      this.scopeData = scope.row
      this.isAddModel = false
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
    },
    handleDelete({ $index, row }) {
      this.$confirm('确认要删除这个类型吗?', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const data = {
            id: row.id
          }
          await deleteCarType(data)
          this.list.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succeed!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    async confirm() {
      const isEdit = this.dialogType === 'edit'
      console.log(isEdit)
      const data = this.scopeData
      const res = await insertOrUpdateCarType(data)
      await this.getList()
      const { id } = res
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `
            <div>类型ID: ${id}</div>
          `,
        type: 'success'
      })
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.scopeData.imgUrl = res.data
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      return true
      // const isJPG = file.type === 'image/jpeg'
      // const isLt2M = file.size / 1024 / 1024 < 2
      //
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
